/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.core.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.grayrabbit.pay.chinapnr.Chinapnr;
import org.grayrabbit.pay.chinapnr.common.PnrConstants;
import org.grayrabbit.pay.chinapnr.config.ChinapnrConfigUtil;
import org.grayrabbit.pay.core.biz.manager.trade.ChinaPnrTradeManager;
import org.grayrabbit.pay.core.model.common.SystemConstants;
import org.grayrabbit.pay.core.model.entity.transaction.Trade;
import org.grayrabbit.pay.core.model.enums.TradeEnum;
import org.grayrabbit.pay.core.model.exception.PayException;
import org.grayrabbit.pay.core.model.results.PayResult;
import org.grayrabbit.web.struts2.GenericAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 汇付交易结果处理类
 * 
 * @author wy
 * @version $Id: PnrTradeResultAction.java, v 0.1 2012-11-6 下午4:52:06 wy Exp $
 */
@Actions
public class PnrTradeResultAction extends GenericAction {

    /** serialVersionUID */
    private static final long    serialVersionUID = -3382597772976956928L;

    private static final Logger  LOG              = LoggerFactory
                                                      .getLogger(PnrTradeResultAction.class);

    @Autowired
    private ChinaPnrTradeManager chinaPnrTradeManager;

    @Action("pnr_trade_result")
    public String execute() {
        try {
            String cmdId = getRequest().getParameter("CmdId"); //消息类型
            LOG.info("CmdId{}", cmdId);
            String merId = getRequest().getParameter("MerId"); //商户号
            String respCode = getRequest().getParameter("RespCode"); //应答返回码
            String trxId = getRequest().getParameter("TrxId"); //钱管家交易唯一标识
            String ordAmt = getRequest().getParameter("OrdAmt"); //金额
            String curCode = getRequest().getParameter("CurCode"); //币种
            String pid = getRequest().getParameter("Pid"); //商品编号
            String ordId = getRequest().getParameter("OrdId"); //订单号
            String merPriv = getRequest().getParameter("MerPriv"); //商户私有域
            String retType = getRequest().getParameter("RetType"); //返回类型
            String divDetails = getRequest().getParameter("DivDetails"); //分账明细
            String gateId = getRequest().getParameter("GateId"); //银行ID
            String chkValue = getRequest().getParameter("ChkValue"); //签名信息 

            String merData = cmdId + merId + respCode + trxId + ordAmt + curCode + pid + ordId
                             + merPriv + retType + divDetails + gateId; //参数顺序不能错
            LOG.info("TRADE汇付 CmdId:{}", cmdId);
            LOG.info("TRADE汇付 merId:{}", merId);
            LOG.info("TRADE汇付 respCode:{}", respCode);
            LOG.info("TRADE汇付 trxId:{}", trxId);
            LOG.info("TRADE汇付 ordAmt:{}", ordAmt);
            LOG.info("TRADE汇付 curCode:{}", curCode);
            LOG.info("TRADE汇付 pid:{}", pid);
            LOG.info("TRADE汇付 ordId:{}", ordId);
            LOG.info("TRADE汇付 merPriv:{}", merPriv);
            LOG.info("TRADE汇付 retType:{}", retType);
            LOG.info("TRADE汇付 divDetails:{}", divDetails);
            LOG.info("TRADE汇付 gateId:{}", gateId);
            LOG.info("TRADE汇付 chkValue:{}", chkValue);

            if (!ChinapnrConfigUtil.getChinapnrInfo().getMemId().equals(merId)) {
                LOG.info("TRADE汇付 返回MemId不正确,实际为:{}，应为{}", merId, ChinapnrConfigUtil
                    .getChinapnrInfo().getMemId());
                throw new PayException("返回MemId不正确");
            }

            boolean signFlag = Chinapnr.veriSignMsg(merData, chkValue);

            LOG.info("TRADE汇付 订单{}验证签名状态:{}", ordId, signFlag);
            if (!signFlag) {
                throw new PayException("验证签名失败");
            } else {
                //他妹的文档上两个都由，但其他都不为00，都写上
                boolean tradeSuccess = "000000".equals(respCode) || "00".equals(respCode);
                final Trade trade = new Trade();

                if (tradeSuccess) {
                    LOG.info("TRADE汇付 接收订单号为{}的交易成功", ordId);
                    trade.setStatusEnum(TradeEnum.PAY_SUCCESS);
                } else {
                    LOG.info("TRADE汇付 接收订单号为{}的交易失败", ordId);
                    LOG.info("TRADE汇付 接收订单号为{}的交易失败", ordId);
                    trade.setMemo("失败原因"+PnrConstants.TRADE_FAIL_MAP.get(respCode));
                    trade.setStatusEnum(TradeEnum.PAY_FAIL);
                }
                trade.setOrderTradeId(ordId);
                trade.setTradeAction(SystemConstants.ACTION_PAY);
                PayResult result = chinaPnrTradeManager.updateChinapnr(trade);
                if (!result.isSuccess()) {
                    LOG.info("TRADE汇付 接收订单号为{}的交易后台处理出错,{}", ordId, result.getResultMsg());
                    throw new PayException(result.getResultCode(), result.getResultMsg());
                }
                return renderHtml("RECV_ORD_ID_" + ordId);
            }
        } catch (Exception e) {
            LOG.info("接收汇付交易结果处理出错:{}", e.getMessage());
            throw new PayException("接收汇付交易结果处理出错");
        }

    }

}
